import { reactive } from 'vue'
import { userStore } from '@/store/user.store'

interface LocationParams {
  code?: string
  state?: string
}

export default function useOpenAuthSignin (authApi: (data: any) => Promise<string>) {
  const locationParams = reactive<LocationParams>({})

  const getWindowLocationParams = async (): Promise<void> => {
    const searchParams = window.location.search.substring(1)
    const paramPairs = searchParams.split('&')

    paramPairs.forEach(pair => {
      if (pair) {
        const [key, value] = pair.split('=')
        locationParams[key] = decodeURIComponent(value || '')
      }
    })
  }

  getWindowLocationParams()

  const handleOpenAuthSignin = async () => {
    try {
      const token = await authApi(locationParams)
      window.localStorage.setItem('token', token)
      await userStore().queryUserProfile()
      location.replace(locationParams.state || '/home')
    } catch (error) {
      setTimeout(() => {
        location.replace('/signin')
      }, 1000)
    }
  }

  handleOpenAuthSignin()
}
